﻿using System;
using Missbot.Common;
using Missbot.Service;

namespace Missbot.AIModule.Gaming.Lottery
{
    public class LotteryRecord : DbBaseEntity
    {
        public string DataStr { get; init; }

        public int Count { get; set; }

        public int TotalPlus { get; set; }

        public int TotalMinus { get; set; }
    }

    public static class LotteryRecordDA
    {
        public static string Format(this LotteryRecord entity)
        {
            var msgs = new[]
            {
                $"共计开箱子 {entity.Count} 次",
                $"总盈利 {entity.TotalPlus.CurencyFormat()}",
                $"总亏损 {entity.TotalMinus.CurencyFormat()}",
                $"合计 {(entity.TotalPlus > entity.TotalMinus ? "+" : "")}{(entity.TotalPlus - entity.TotalMinus).CurencyFormat()}"
            };
            return string.Join("\n", msgs);
        }

        public static LotteryRecord GetToday()
        {
            var dateStr = DateTime.Now.ToString("yyyyMMdd");
            var record = MongoService<LotteryRecord>.GetOnly(p => p.DataStr == dateStr);
            if (record != null)
            {
                return record;
            }

            record = new LotteryRecord { DataStr = dateStr };

            MongoService<LotteryRecord>.Insert(record);
            return record;
        }

        public static LotteryRecord GetYesterday()
        {
            var dateStr = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
            var record = MongoService<LotteryRecord>.GetOnly(p => p.DataStr == dateStr);
            if (record != null)
            {
                return record;
            }

            record = new LotteryRecord { DataStr = dateStr };

            MongoService<LotteryRecord>.Insert(record);
            return record;
        }

        public static void Record(int absBonus)
        {
            var todayRec = GetToday();
            todayRec.Count++;
            if (absBonus > 0)
            {
                todayRec.TotalPlus += absBonus;
            }
            else
            {
                todayRec.TotalMinus += Math.Abs(absBonus);
            }

            todayRec.Update();
        }

        public static void Update(this LotteryRecord entity)
        {
            MongoService<LotteryRecord>.Update(entity);
        }
    }
}